﻿using CommonLib.Properties;
using System.Collections.Generic;
using System.Linq;
using System.Xml;

namespace CommonLib.Util;

public static class TypeConvertor
{
    private static readonly Dictionary<string, string> BefType;

    private static readonly Dictionary<string, string> BefNewType;

    private static readonly Dictionary<string, string> AftType;

    static TypeConvertor()
    {
        var doc = new XmlDocument();
        doc.LoadXml(Resources.BeforeDataType);
        var root = doc.DocumentElement;
        BefType = [];
        BefNewType = [];
        foreach (XmlNode node in root!.ChildNodes)
        {
            if (!node.Name.Equals(ConstUtil.Before)) continue;
            foreach (XmlNode sn in node!.ChildNodes)
            {
                BefType[sn.Name] = sn.InnerText;
            }
        }
        doc = new XmlDocument();
        doc.LoadXml(Resources.AfterDataType);
        root = doc.DocumentElement;
        AftType = [];
        foreach (XmlNode node in root!.ChildNodes)
        {
            if (!node.Name.Equals(ConstUtil.After)) continue;
            foreach (XmlNode sn in node!.ChildNodes)
            {
                AftType[sn.Name] = sn.InnerText;
            }
        }
    }


    public static string NewType(string old)
    {
        var type = old;
        string end = string.Empty;
        if (type.Contains('('))
        {
            type = type[..type.IndexOf('(')].Trim();
            end = old[old.IndexOf('(')..];
        }
        var key = BefType.Keys.FirstOrDefault(s => s.EqualsIgnoreCase(type));
        if (key != null) return $"{AftType[BefType[key]]}{end}";
        return string.Empty;
    }

    public static bool IsBaseType(string type)
    {
        if (type.Contains('(')) type = type[..type.IndexOf('(')].Trim();
        return BefType.Keys.Any(s => s.EqualsIgnoreCase(type));
    }

    public static void AddNew(string name, string value)
    {
        BefNewType.Add(name, value);
    }
}
